package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.entity.Result;
import com.itheima.pojo.Brand;
import com.itheima.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.itheima.entity.StatusCode.ERROR;
import static com.itheima.entity.StatusCode.OK;

@RestController
@RequestMapping("/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    //findAll
    @RequestMapping("/findAll")
    public Result findAll(){
        List<Brand> list = brandService.list();
        return new Result(true, OK,null,list);
    }
    //findById
    @RequestMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id){
        Brand brand = brandService.getById(id);
        return new Result(true, OK,null,brand);
    }
    //findPage
    @RequestMapping("/search/{page}/{size}")
    public Result findPage(@PathVariable("page") Integer page,
                           @PathVariable("size") Integer size){
        IPage<Brand> page1 = new Page<>(page, size);
        IPage<Brand> brandIPage = brandService.page(page1);
        List<Brand> list = brandIPage.getRecords();
        return new Result(true, OK,null,list);
    }

    //add
    @PostMapping("/add")
    public Result add(@RequestBody Brand brand){
        boolean b = brandService.save(brand);
        if(b){
            return new Result(true, OK,"添加成功",null);
        }
        return new Result(false, ERROR,"添加失败",null);
    }
    //update
    @PutMapping("update")
    public Result update(@RequestBody Brand brand){
        boolean b = brandService.updateById(brand);
        if(b){
            return new Result(true, OK,"修改成功",null);
        }
        return new Result(false, ERROR,"修改失败",null);
    }
    //delete
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id){
        boolean b = brandService.removeById(id);
        if(b){
            return new Result(true, OK,"删除成功",null);
        }
        return new Result(false, ERROR,"删除失败",null);
    }

}
